package com.hjf.ditubiaozhu.base.recycler;

import android.content.Context;
import android.support.annotation.IntDef;
import android.support.annotation.StringRes;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.hjf.ditubiaozhu.R;
import com.hjf.ditubiaozhu.base.Base;
import com.hjf.ditubiaozhu.base.BaseFragment;
import com.hjf.ditubiaozhu.base.ImageLoadHelper;
import com.hjf.ditubiaozhu.base.recycler.BaseSwipeAdapter.*;

import com.hjf.ditubiaozhu.utils.ToastUtils;

/**
 * Created by hejianfeng on 17/1/25.
 */

public abstract class BaseSwipeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
        implements SwipeHelper<LoadHolder, MoreHolder> {

    /**
     * 抄Toast的,约束变量的,哈哈
     */
    @IntDef({LOAD_STATUS_COMPLETE, LOAD_STATUS_DOWN, LOAD_STATUS_UP, LOAD_STATUS_NET_ERROR})
    @Retention(RetentionPolicy.SOURCE)
    public @interface LoadStatus {
    }

    //随便写的,防止和自定义的重复
    private static final int ITEM_LOAD = -1580067;
    private static final int ITEM_MORE = -1076187;

    final public LayoutInflater mLayoutInflater;
    //模型数据
    private List<Base> mList = new ArrayList<>();

    protected OnItemClickListener mOnItemClickListener;
    protected OnItemLongClickListener<Base> mOnItemLongClickListener;
    private OnInsideRefreshListener mOnRefreshListener;
    protected ImageLoadHelper mImageLoadHelper;

    private int mLoadStatus = -1;//-1:初始化;   0:加载完成;  1:下拉刷新;  2:加载更多;  3:加载出错
    public static final int LOAD_STATUS_COMPLETE = 0;// 复位到正常状态
    public static final int LOAD_STATUS_DOWN = 1;// 下拉刷新需要  清空
    public static final int LOAD_STATUS_UP = 2;// 加载更多  需要 追加在后面
    public static final int LOAD_STATUS_NET_ERROR = 3;//错误

    private boolean mHasMore;//是否有更多选项
    protected Context mContext;//protected属性让子类用

    public BaseSwipeAdapter(BaseFragment baseFragment) {
        mContext = baseFragment.getActivity();
        mImageLoadHelper = baseFragment;
        mLayoutInflater = LayoutInflater.from(mContext);
    }


    /**
     * 设置单击事件
     *
     * @param onItemClickListener
     */
    public void setmOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    /**
     * 设置长按点击事件
     *
     * @param onItemLongClickListener
     */
    public void setmOnLongItemClickListener(OnItemLongClickListener<Base> onItemLongClickListener) {
        mOnItemLongClickListener = onItemLongClickListener;
    }

    public void setImageLoadHelper(ImageLoadHelper imageLoadHelper) {
        mImageLoadHelper = imageLoadHelper;
    }

    /**
     * 设置刷新回调
     */
    public void setmOnRefreshListener(OnInsideRefreshListener mOnRefreshListener) {
        this.mOnRefreshListener = mOnRefreshListener;
    }


    /**
     * 加载单一类型数据
     * 1. 第一次加载,
     * 2. 下拉刷新加载.
     * ----1. 全新加载,同1
     * ----2. 覆盖加载,合并数据
     * 3. 上拉加载更多,覆盖加载,合并数据,同2.2
     * <p>
     * 2种情况,1是清空加载. 2是合并加载.
     */
    public void load() {

    }

    /**
     * 加载多种类型数据
     * 1. 第一次加载,
     * 2. 下拉刷新加载.
     * ----1. 全新加载,同1
     * ----2. 覆盖加载,合并数据
     * 3. 上拉加载更多,覆盖加载,合并数据,同2.2
     * <p>
     * 2种情况,1是清空加载. 2是合并加载.
     */
    public void load(int t) {

    }

    /**
     * 那些需要继承者子类定:类型总数:typeCount,类型索引
     */

    public <T extends Base> T getModel(int position) {
        return (T) mList.get(position);
    }

    public int getModelSize() {
        return mList.size();
    }


    public void clearModelAll() {
        mList.clear();
    }

    public void sortModel() {
        Collections.sort(mList);
    }


    /*
    * @param temp  每次请求到的数据
    * @param total 列表数据的总数
    */
    public void load(List<Base> temp, int total) {

        mOnRefreshListener.refreshComplete();
        switch (mLoadStatus) {
            case LOAD_STATUS_DOWN:
                setLoadStatus(LOAD_STATUS_COMPLETE);

                clearModelAll();
                if (temp != null) {
                    mList.addAll(temp);
                }
                mHasMore = getModelSize() < total;
                sortModel();
                notifyDataSetChanged();
                break;
            case LOAD_STATUS_UP:
                setLoadStatus(LOAD_STATUS_COMPLETE);
                if (temp == null) {
                    mHasMore = getModelSize() < total;
                    notifyDataSetChanged();
                } else {
                    mList.addAll(temp);
                    sortModel();
                    mHasMore = getModelSize() < total;
                    notifyDataSetChanged();
                    if (mHasMore) {
                        notifyDataSetChanged();
                        notifyItemRangeInserted(getItemCount() - temp.size(), getModelSize());
                    } else {
                        notifyItemRangeChanged(getModelSize() - temp.size(), getModelSize());
                        ToastUtils.showToast(mContext, R.string.swipe_not_lodemore);
                    }
                }
                break;
            default:
                break;
        }
    }


    /**
     * 刷新错误
     */
    public void error() {
        mOnRefreshListener.refreshComplete();
        switch (mLoadStatus) {
            case 1:
                setLoadStatus(LOAD_STATUS_NET_ERROR);
                reset();
                break;
            case 2:
                setLoadStatus(LOAD_STATUS_NET_ERROR);
                notifyItemChanged(getModelSize());
                break;
            default:
                break;
        }
    }

    /**
     * 重置
     */
    public void reset() {
        clearModelAll();
        notifyDataSetChanged();
    }


    @Override
    public int getItemViewType(int position) {
        int userDataSize = getModelSize();
        // 没数据时:sdd
        if (userDataSize == 0) {
            return ITEM_LOAD;
        } else {
            return position < userDataSize ? getUserItemViewType(position) : ITEM_MORE;
        }
    }

    /**
     * 用户的ItemViewType
     */

    protected int getUserItemViewType(int position) {
        return getModel(position).getTypeInt();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ITEM_LOAD:
                return loadViewHolder(parent);
            case ITEM_MORE:
                return moreViewHolder(parent);
            default:

                 return onCreateUserViewHolder(parent, viewType);
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case ITEM_LOAD:
                bindLoadViewHolder((LoadHolder) holder);
                break;
            case ITEM_MORE:
                bindMoreViewHolder((MoreHolder) holder);
                break;
            default:
                bindUserViewHolder(holder, position);//bind外界的的VH

                if (mOnItemClickListener != null)
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mOnItemClickListener.itemClick(view, holder.getAdapterPosition(), getModel(holder.getAdapterPosition()));
                        }
                    });
                if (mOnItemLongClickListener != null)
                    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            mOnItemClickListener.itemClick(view, holder.getAdapterPosition(), getModel(holder.getAdapterPosition()));
                            return true;
                        }

                        ;
                    });
                break;
        }
    }

    /**
     * 用户数据为空,则显示默认页面
     */
    @Override
    public int getItemCount() {
        int userDataSize = getModelSize();

        return userDataSize == 0 ? 1 : mHasMore ? userDataSize + 1 : userDataSize;
    }

    @Override
    public LoadHolder loadViewHolder(ViewGroup parent) {
        return new LoadHolder(mLayoutInflater.inflate(R.layout.item_swipe_def, parent, false));
    }

    @Override
    public MoreHolder moreViewHolder(ViewGroup parent) {
        return new MoreHolder(mLayoutInflater.inflate(R.layout.item_swipe_more, parent, false));
    }

    @Override
    public void bindLoadViewHolder(LoadHolder holder) {
        switch (mLoadStatus) {
            case LOAD_STATUS_COMPLETE:
                holder.mAtvSwipeLoad.setVisibility(View.VISIBLE);
                holder.mAtvSwipeLoad.setText(defText());
                break;
            case LOAD_STATUS_NET_ERROR:
                holder.mAtvSwipeLoad.setVisibility(View.VISIBLE);
                holder.mAtvSwipeLoad.setText(defErrorText());
                break;
            default:
                holder.mAtvSwipeLoad.setVisibility(View.GONE);
                break;
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mLoadStatus == LOAD_STATUS_NET_ERROR) {
                    setLoadStatus(LOAD_STATUS_DOWN);
                    notifyItemChanged(0);
                    mOnRefreshListener.downRefresh();
                }
            }
        });
    }

    @Override
    public void bindMoreViewHolder(MoreHolder holder) {
        switch (mLoadStatus) {
            case 3:
                holder.mAtvSwipeMore.setText(moreErrorText());
                holder.mPbSwipeMore.setVisibility(View.GONE);
                break;
            default:
                holder.mAtvSwipeMore.setText(moreText());
                holder.mPbSwipeMore.setVisibility(View.VISIBLE);
                break;
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mLoadStatus == LOAD_STATUS_NET_ERROR) {
                    setLoadStatus(LOAD_STATUS_UP);
                    notifyItemChanged(getModelSize());
                    mOnRefreshListener.upRefresh(getModelSize());

                }
            }
        });
    }

    @Override
    public int userDataCount() {
        return getModelSize();
    }

    /**
     * 设置加载状态
     */
    public void setLoadStatus(@LoadStatus int loadStatus) {
        mLoadStatus = loadStatus;
    }

    /**
     * 加载状态
     */
    public int getLoadStatus() {
        return mLoadStatus;
    }

    /**
     * 是否有更多
     */
    public boolean isHasMore() {
        return mHasMore;
    }

    /**
     * 没有数据时显示的默认文本
     */
    @StringRes
    protected int defText() {
        return R.string.swipe_def_sale;
    }

    /**
     * 加载出错显示文本
     */
    @StringRes
    @SuppressWarnings("all")
    protected int defErrorText() {
        return R.string.swipe_def_error;
    }

    /**
     * 更多加载显示的默认文本
     */
    @StringRes
    @SuppressWarnings("all")
    protected int moreText() {
        return R.string.swipe_loading_more;
    }

    /**
     * 加载更多出错显示的文本
     */
    @StringRes
    @SuppressWarnings("all")
    protected int moreErrorText() {
        return R.string.swipe_loading_error;
    }

    /**
     * 用户{@link android.support.v7.widget.RecyclerView.ViewHolder}转化
     */
    protected <UserVH extends MyViewHolder> UserVH castVH(RecyclerView.ViewHolder holder) {
        return (UserVH) holder;
    }

    /**
     * 用户{@link android.support.v7.widget.RecyclerView.ViewHolder}转化
     */
    public <T extends Base> T castModel(Object holder) {
        return (T) holder;
    }

    /**
     * 设置文本
     */
    public void setText(TextView textview, String text) {

        if (text == null) text = "";

        if (textview != null) textview.setText(text);
    }


    public static class MoreHolder extends RecyclerView.ViewHolder {

        public AppCompatTextView mAtvSwipeMore;
        public ProgressBar mPbSwipeMore;

        public MoreHolder(View itemView) {
            super(itemView);

            mAtvSwipeMore = (AppCompatTextView) itemView.findViewById(R.id.atv_swipe_more);
            mPbSwipeMore = (ProgressBar) itemView.findViewById(R.id.pb_swipe_more);
        }
    }

    public static class LoadHolder extends RecyclerView.ViewHolder {

        public ImageView mImgSwipeLoad;
        public AppCompatTextView mAtvSwipeLoad;

        public LoadHolder(View itemView) {
            super(itemView);
            mImgSwipeLoad = (ImageView) itemView.findViewById(R.id.img_swipe_def);
            mAtvSwipeLoad = (AppCompatTextView) itemView.findViewById(R.id.atv_swipe_def);
        }
    }
}
